package com.microservice.skeleton.auth.config;

import com.microservice.skeleton.common.vo.UserVo;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.BadClientCredentialsException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author: lijin
 * @date: 2018年10月01日
 */
public class SimpleAuthenticationProvider implements AuthenticationProvider {


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getPrincipal() == null ? "" : authentication.getName();

        if (username.equals("admin")) throw new BadCredentialsException("==============");
        String password = authentication.getCredentials() == null ? "" : authentication.getCredentials().toString();


        Map<String, Object> details = (Map<String, Object>) authentication.getDetails();

        Object account_type = details.get("account_type");
        if(account_type == null) throw new InvalidGrantException("account_type is required");
        Integer accountType = Integer.valueOf(account_type.toString());


        switch (accountType){
            case 1:

                break;
            case 2:

                break;
            default:
                throw new BadClientCredentialsException();

        }

        UserVo userVo = new UserVo();
        userVo.setId(1234);

        details.put("accountId", userVo.getId());
        details.put("accountType", accountType);
        details.put("authorities", new HashSet<>());
        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
                details, authentication.getCredentials(),
                new HashSet<>());
        result.setDetails(details);
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
